package cc.mrbird.febs.server.referral.utils;

import cc.mrbird.febs.server.referral.entity.OAuthToken;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;

@Slf4j

public class AuthUtils {

    public static OAuthToken getOAuthInfo(String username, String password, String url){
        log.info("userOAuthUri:" + url);
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("grant_type", "password"));
        params.add(new BasicNameValuePair("username", username));
        params.add(new BasicNameValuePair("password", password));
        List<HashMap<String, Object>> headerMapList = new ArrayList<>();
        HashMap<String, Object> headerMap = new LinkedHashMap<>();
        headerMap.put("key", "Authorization");
        headerMap.put("value", "Basic ZmViczoxMjM0NTY=");
        headerMapList.add(headerMap);
        String resultStr = doPostFormData(url, params, headerMapList);
        JSONObject resultJson = JSON.parseObject(resultStr);
        OAuthToken oAuthToken = resultJson.toJavaObject(OAuthToken.class);
        return (null != oAuthToken.getAccessToken()) ? oAuthToken : null;
    }



    public static String doGetFormData(String url, List<NameValuePair> params, List<HashMap<String, Object>> headerMapList){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String result = "";
        CloseableHttpResponse response = null;
        StringBuffer paramBuffer = new StringBuffer();
        for(int i = 0; i < params.size(); i++){
            NameValuePair nameValuePair = params.get(i);
            String con = (i == 0) ? "?" : "&";
            paramBuffer.append(con);
            paramBuffer.append(nameValuePair.getName());
            paramBuffer.append("=");
            paramBuffer.append(nameValuePair.getValue());
        }
        url += paramBuffer;
        log.info("get url:" + url);
        try {
            HttpGet httpGet = new HttpGet(url);
            if(null != headerMapList && headerMapList.size() > 0){
                for(int i = 0; i < headerMapList.size(); i++){
                    HashMap<String, Object> headerMap = headerMapList.get(i);
                    httpGet.addHeader(headerMap.get("key").toString(), headerMap.get("value").toString());
                }
            }
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            log.info("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                log.info("响应内容长度为:" + responseEntity.getContentLength());
                result = EntityUtils.toString(responseEntity);
                log.info("响应内容为:" + result);
            }
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
        finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String doPostFormData(String url, List<NameValuePair> params, List<HashMap<String, Object>> headerMapList){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String result = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            if(null != headerMapList && headerMapList.size() > 0){
                for(int i = 0; i < headerMapList.size(); i++){
                    HashMap<String, Object> headerMap = headerMapList.get(i);
                    httpPost.addHeader(headerMap.get("key").toString(), headerMap.get("value").toString());
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8")); // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            log.info("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                log.info("响应内容长度为:" + responseEntity.getContentLength());
                result = EntityUtils.toString(responseEntity);
                log.info("响应内容为:" + result);
            }
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
        finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


}
